<template>
    <div>
        <el-card shadow="never" :body-style="{ padding: '20px' }">
            <el-form :model="formData" ref="form" label-width="120px" :inline="false">
                <!-- 基本信息区域 -->
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划编码">
                            <el-input v-model="formData.planCode" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划名称">
                            <el-input v-model="formData.planName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划类型">
                            <el-radio-group v-model="formData.planType" disabled>
                                <el-radio value="1">订单计划</el-radio>
                                <el-radio value="2">库存计划</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item v-if="formData.planType == 1" label="订单编号">
                            <el-input v-model="formData.orderNo" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 产品信息区域 -->
                <el-divider content-position="left">产品信息</el-divider>

                <!-- 产品列表表格 -->
                <el-table :data="formData.products" border style="width: 100%; margin-bottom: 20px;"
                    v-loading="loading">
                    <el-table-column prop="productCode" label="产品编号" width="150" />
                    <el-table-column prop="productName" label="产品名称" width="150" />
                    <el-table-column prop="specification" label="规格型号" width="150" />
                    <el-table-column prop="unit" label="单位" width="100" />
                    <el-table-column prop="quantity" label="计划数量" width="120">
                        <template #default="{ row }">
                            <el-tag>{{ row.quantity }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="producedNum" label="已生产数量" width="120">
                        <template #default="{ row }">
                            <el-tag :type="row.producedNum >= row.quantity ? 'success' : 'warning'">
                                {{ row.producedNum }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="progress" label="完成进度" width="150">
                        <template #default="{ row }">
                            <el-progress :percentage="Math.min(100, Math.round((row.producedNum / row.quantity) * 100))"
                                :status="row.producedNum >= row.quantity ? 'success' : ''" />
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 客户信息区域 -->
                <el-divider v-if="formData.planType == 1" content-position="left">客户信息</el-divider>
                <el-row :gutter="20" v-if="formData.planType == 1">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="客户编号">
                            <el-input v-model="formData.customerCode" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="客户名称">
                            <el-input v-model="formData.customerName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 计划时间信息 -->
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划开始日期">
                            <el-date-picker v-model="formData.planStart" type="date" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划结束日期">
                            <el-date-picker v-model="formData.planEnd" type="date" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <!-- BOM需求、物料需求选项卡 -->
            <el-tabs v-model="activeName" type="border-card" class="detail-tabs">
                <!-- 按产品分组的BOM需求 -->
                <el-tab-pane v-for="product in formData.products" :key="product.productCode"
                    :label="`${product.productName} BOM需求`" :name="`bom-${product.productCode}`">
                    <el-table :data="getBomData(product.productCode)" border style="width: 100%" v-loading="loading">
                        <el-table-column prop="materialCode" label="物料编号" />
                        <el-table-column prop="materialName" label="物料名称" />
                        <el-table-column prop="specification" label="规格型号" />
                        <el-table-column prop="unit" label="单位" />
                        <el-table-column prop="materialType" label="物料/产品" />
                        <el-table-column prop="totalQuantity" label="预计使用量" />
                        <el-table-column prop="requiredDate" label="需求日期" />
                    </el-table>
                </el-tab-pane>

                <!-- 汇总的物料需求 -->
                <el-tab-pane label="汇总物料需求" name="material">
                    <el-table :data="materialData" border style="width: 100%" v-loading="loading">
                        <el-table-column prop="materialCode" label="物料编号" />
                        <el-table-column prop="materialName" label="物料名称" />
                        <el-table-column prop="specification" label="规格型号" />
                        <el-table-column prop="unit" label="单位" />
                        <el-table-column prop="materialType" label="物料/产品" />
                        <el-table-column label="总需求量">
                            <template #default="{ row }">
                                {{ row.totalQuantity }}
                                <el-tag v-if="row.inventory !== undefined"
                                    :type="row.inventory >= row.totalQuantity ? 'success' : 'danger'" size="small">
                                    库存: {{ row.inventory }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="缺口量" v-if="hasInventoryData">
                            <template #default="{ row }">
                                <span v-if="row.inventory !== undefined">
                                    {{ Math.max(0, row.totalQuantity - row.inventory) }}
                                </span>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="requiredDate" label="需求日期" />
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <div class="detail-footer">
                <el-button type="primary" >关闭</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, computed, onMounted } from 'vue'

import { useRouter } from 'vue-router'

const router = useRouter()

let emits = defineEmits(['ref-table'])
let props = defineProps(["data"])

// 表单数据
const formData = ref({
    id: 1,
    planCode: 'JH20230701',
    planName: '7月生产计划-产品A',
    planType: '1',
    orderNo: 'SO2023070101',
    customerCode: 'C-10086',
    customerName: '华为技术有限公司',
    planStart: '2023-08-15',
    planEnd: '2023-08-31',
    planStatus: '生产中',
    // 产品列表
    products: [
        {
            productCode: 'P-1001',
            productName: '智能控制器',
            specification: 'IC-1001-A',
            unit: '个',
            quantity: 1000,
            producedNum: 350
        },
        {
            productCode: 'P-1002',
            productName: '智能传感器',
            specification: 'IS-1002-B',
            unit: '个',
            quantity: 500,
            producedNum: 200
        }
    ]
})

const loading = ref(false)

// 产品BOM数据定义
const productBoms = ref({
    // 产品1的BOM
    'P-1001': [
        {
            materialCode: 'M-2001',
            materialName: 'PCB主板',
            specification: 'PCB-2001',
            unit: '块',
            materialType: '物料',
            perQuantity: 1, // 每个产品需要1个
            inventory: 120 // 当前库存
        },
        {
            materialCode: 'M-2002',
            materialName: '芯片组',
            specification: 'IC-2002',
            unit: '套',
            materialType: '物料',
            perQuantity: 1,
            inventory: 80
        },
        {
            materialCode: 'P-1002', // 子产品
            materialName: '智能传感器',
            specification: 'IS-1002-B',
            unit: '个',
            materialType: '产品',
            perQuantity: 2,
            inventory: 50
        }
    ],
    // 产品2的BOM
    'P-1002': [
        {
            materialCode: 'M-2003',
            materialName: '传感器模块',
            specification: 'SENSOR-2003',
            unit: '个',
            materialType: '物料',
            perQuantity: 1,
            inventory: 60
        },
        {
            materialCode: 'M-2004',
            materialName: '连接器',
            specification: 'CONN-2004',
            unit: '个',
            materialType: '物料',
            perQuantity: 4,
            inventory: 200
        }
    ]
})

// 公共物料
const commonMaterials = ref([
    {
        materialCode: 'M-2005',
        materialName: '包装材料',
        specification: 'PACK-2005',
        unit: '套',
        materialType: '物料',
        perQuantity: 1,
        inventory: 300
    },
    {
        materialCode: 'M-2006',
        materialName: '说明书',
        specification: 'MANUAL-2006',
        unit: '份',
        materialType: '物料',
        perQuantity: 1,
        inventory: 250
    }
])

// 获取指定产品的BOM数据
const getBomData = (productCode) => {
    const product = formData.value.products.find(p => p.productCode === productCode)
    if (!product || !productBoms.value[productCode]) return []
    
    return productBoms.value[productCode].map(item => ({
        ...item,
        totalQuantity: item.perQuantity * product.quantity,
        requiredDate: formData.value.planStart
    }))
}

// 检查是否有库存数据
const hasInventoryData = computed(() => {
    return Object.values(productBoms.value).flat().some(item => item.inventory !== undefined) || 
           commonMaterials.value.some(item => item.inventory !== undefined)
})

// 计算汇总物料需求
const materialData = computed(() => {
    const materialMap = new Map()
    
    // 汇总各产品的BOM需求
    formData.value.products.forEach(product => {
        const bomList = productBoms.value[product.productCode] || []
        bomList.forEach(item => {
            const key = `${item.materialCode}-${item.specification}`
            const existing = materialMap.get(key)
            const quantity = item.perQuantity * product.quantity
            
            if (existing) {
                existing.totalQuantity += quantity
                // 取最早的需求日期
                if (new Date(formData.value.planStart) < new Date(existing.requiredDate)) {
                    existing.requiredDate = formData.value.planStart
                }
            } else {
                materialMap.set(key, {
                    ...item,
                    totalQuantity: quantity,
                    requiredDate: formData.value.planStart
                })
            }
        })
    })
    
    // 添加公共物料
    commonMaterials.value.forEach(item => {
        const key = `${item.materialCode}-${item.specification}`
        const totalQuantity = item.perQuantity * formData.value.products.reduce((sum, p) => sum + p.quantity, 0)
        const existing = materialMap.get(key)
        
        if (existing) {
            existing.totalQuantity += totalQuantity
        } else {
            materialMap.set(key, {
                ...item,
                totalQuantity: totalQuantity,
                requiredDate: formData.value.planEnd // 公共物料通常在最后需要
            })
        }
    })
    
    return Array.from(materialMap.values())
})

// 初始化激活的标签页
const activeName = ref(`bom-${formData.value.products[0]?.productCode || ''}`)
</script>

<style scoped>
/* 新增样式 */
.material-warning {
    color: #f56c6c;
    font-weight: bold;
}

.material-safe {
    color: #67c23a;
}

.tab-label {
    display: flex;
    align-items: center;
}
.tab-label .el-tag {
    margin-left: 8px;
}
</style>